package com.xoa.controller.document;

import com.xoa.controller.enclosure.EnclosureController;
import com.xoa.controller.work.WorkController;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.document.DocumentExchangeReceiveMapper;
import com.xoa.dao.document.DocumentExchangeSetMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.document.DocumentOutConfigMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.common.SysPara;
import com.xoa.model.document.*;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowHookWithBLOBs;
import com.xoa.model.workflow.FlowRun;
import com.xoa.service.common.SysCodeService;
import com.xoa.service.document.DocumentExchangeOutUnitService;
import com.xoa.service.document.DocumentExchangeReceiveService;
import com.xoa.service.document.DocumentOutSendRecordService;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.flowhook.FlowHookService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import com.yirong.exchange.bll.ClientReceive1;
import com.yirong.exchange.bll.ClientSend;
import com.yirong.exchange.bll.ClientSend1;
import com.yirong.exchange.model.Accessory;
import com.yirong.exchange.model.Document;
import com.yirong.exchange.model.DocumentImpl;
import com.yirong.exchange.model.Reference;
import com.yirong.exchange.util.DateTime;
import com.yirong.exchange.util.StringUtil;
import com.yirong.exchange.util.json.JSONArray;
import com.yirong.exchange.util.json.JSONObject;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import static com.yirong.exchange.bll.ClientParent.*;

@Controller
@RequestMapping("/documentExchangeReceive")
public class DocumentExchangeReceiveController {
    @Resource
    private DocumentExchangeReceiveService documentExchangeReceiveService;
    @Resource
    private DocumentExchangeSetMapper documentExchangeSetMapper;
    @Resource
    DocumentSerivce documentSerivce;
    @Resource
    private SmsService smsService;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private EnclosureController enclosureController;
    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    @Resource
    private DocumentOutConfigMapper documentOutConfigMapper;
    @Resource
    private DocumentModelMapper documentModelMapper;
    @Resource
    private DocumentOutSendRecordService documentOutSendRecordService;
    @Resource
    private DocumentExchangeOutUnitService documentExchangeOutUnitService;
    @Resource
    private FlowHookMapper flowHookMapper;
    @Resource
    private FlowRunMapper flowRunMapper;
    @Resource
    private WorkController workController;
    @Resource
    private WorkMapper workMapper;
    @Resource
    private UsersService usersService;
    @Resource
    SysCodeService sysCodeService;
    @Resource
    private SysParaMapper sysParaMapper;
    @Resource
    private DocumentExchangeReceiveMapper documentExchangeReceiveMapper;

    @RequestMapping("/netWorkReceive")//联网收文页面
    public String inAbeyance() {
        return "/app/officialDocument/netWorkReceive";
    }

    //查看某条流程的分发情况lsa
    @RequestMapping("/selectByRunId")
    @ResponseBody
    public ToJson<DocumentExchangeReceive> getRuleById(Integer fromRunId) {
        ToJson<DocumentExchangeReceive> tojson = new ToJson<DocumentExchangeReceive>();
        List<DocumentExchangeReceive> documentExchangeReceives = documentExchangeReceiveService.selectByRunId(fromRunId);
        if (documentExchangeReceives != null && documentExchangeReceives.size() > 0) {
            tojson.setObject(documentExchangeReceives);
        }
        tojson.setMsg("ok");
        tojson.setFlag(0);
        return tojson;
    }

    //公文分发lsa
    @RequestMapping("/insertDocumentReceive")
    @ResponseBody
    public ToJson insert(DocumentExchangeReceive documentExchangeReceive, String exchangeIds) {
        ToJson tojson = new ToJson<DocumentExchangeReceive>();
        String[] stringArr = exchangeIds.split(",");
        for (String str : stringArr) {
            DocumentExchangeSet documentExchangeSet = documentExchangeSetMapper.selectByPrimaryKey(Integer.parseInt(str));
            String[] split = documentExchangeSet.getExchangeUserId().split(",");
            for (String userIds : split) {
                Users users = usersService.selectCountByDeptId(documentExchangeSet.getExchangeDeptId(), userIds);
                if (users!=null) {
                    continue;
                } else {
                    String userName = usersService.getUserNameById(userIds, ",");
                    tojson.setMsg(userName+"不在"+documentExchangeSet.getReceiveUnit()+"的对应部门中！请配置正确后再次发送");
                    tojson.setFlag(1);
                    return tojson;
                }
            }
        }
        
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        //获取当前流程实例
        FlowRun flowRun = flowRunMapper.find(documentExchangeReceive.getFromRunId());
        //获取业务接口
        FlowHookWithBLOBs flowHook = flowHookMapper.queryByHmodule("document", String.valueOf(flowRun.getFlowId()));
        //头表单
        org.jsoup.nodes.Document headDoc = null;
        Map<String, org.jsoup.nodes.Document> documentMap = null;
        documentMap = workController.flowMapping(flowRun);
        headDoc = documentMap.get("headDocument");
        if (flowHook != null) {
            String relation = flowHook.getMap();//映射分割
            String[] mappingArray = relation.split(",");
            List<String> key = new ArrayList<>();
            List<String> value = new ArrayList<>();
            for (String mapping : mappingArray) {
                String[] mappingHeadAndEnd = mapping.split("=>");
                if (mappingHeadAndEnd.length > 1) {
                    String mappingHead = mappingHeadAndEnd[0];//映射头
                    String mappingEnd = mappingHeadAndEnd[1];//映射尾
                    String headData = HtmlUtil.getDocumentName(headDoc, mappingHead);
                    if (headData != null && !headData.trim().equals("")) {
                        value.add(mappingEnd);
                        key.add(headData);
                    }

                }
            }
            List<String> values = new ArrayList<>();
            if (key.size() > 0) {
                Map<String, Object> valueMap = workMapper.getDataValue(key, flowRun.getRunId(), "flow_data_" + flowRun.getFlowId());
                if (valueMap != null) {
                    for (String k : key) {
                        Object v = valueMap.get(k);
                        if (v != null) {
                            values.add(String.valueOf(v));
                        } else {
                            values.add("");
                        }
                    }
                }
            }
            //获取文号，标题
            for (int k = 0; k < key.size(); k++) {
                if ("title".equals(value.get(k))) {
                    documentExchangeReceive.setDocTitle(values.get(k));
                }
                if ("doc_no".equals(value.get(k))) {
                    documentExchangeReceive.setDocNo(values.get(k));
                }
            }
        }
        //当前用户的发文单位设置
        DocumentExchangeSet documentExchangeSet = documentExchangeSetMapper.selectByPrimaryKey(Integer.parseInt(documentExchangeReceive.getFromUnit()));
        for (String ids:stringArr) {
            DocumentExchangeSet documentExchangeSets = documentExchangeSetMapper.selectByPrimaryKey(Integer.parseInt(ids));
            documentExchangeReceive.setFromUnit(documentExchangeSet.getFromUnit());//发文单位
            documentExchangeReceive.setReceiveDeptId(documentExchangeSets.getExchangeDeptId());//接收部门对应的dept_id
            documentExchangeReceive.setReceiveUnit(documentExchangeSets.getReceiveUnit());//接收单位名称
            documentExchangeReceive.setFromTime(new Date());//发送时间
            documentExchangeReceive.setReceiveStatus("0");//接收状态
            documentExchangeReceive.setExchangeId(Integer.parseInt(ids));
            documentExchangeReceiveService.insert(documentExchangeReceive);
            //给接收对应人员添加事务提醒
            SmsBody smsBody = new SmsBody();
            smsBody.setFromId(user.getUserId());
            smsBody.setSendTime(DateFormat.getTime(DateFormat.getStrDate(new Date())));
            smsBody.setIsAttach("0");
            smsBody.setSmsType("70");
            if (documentExchangeReceive.getDocTitle() != null && documentExchangeReceive.getDocTitle() != "") {
                smsBody.setContent("来文接收，单位：" + documentExchangeSet.getFromUnit() + "，标题：" + documentExchangeReceive.getDocTitle());
            } else {
                smsBody.setContent("来文接收，单位：" + documentExchangeSet.getFromUnit() + "，标题：");
            }
            boolean bol = false;
            SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
            if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                    && "dazu".equals(myproject.getParaValue())) {
                bol = true;
            }
            smsBody.setRemindUrl("/document/receive?receiveId=" +documentExchangeReceive.getReceiveId());
            String title =bol ? documentExchangeReceive.getDocTitle() : "您有新的收文需要处理";
            String context = "来文接收" + ":" + documentExchangeReceive.getDocTitle();
            smsService.saveSms(smsBody,documentExchangeSets.getExchangeUserId(), "1", "0", title, context, "");

        }
        
        tojson.setMsg("ok");
        tojson.setFlag(0);
        return tojson;
    }

    //公文补发单位获取lsa
    @RequestMapping("/reinsertDocumentReceive")
    @ResponseBody
    public ToJson reinsertDocumentReceive(String unitType, Integer fromRunId) {
        return documentExchangeReceiveService.reinsertDocumentReceive(unitType, fromRunId);
    }

    // 查询列表接口
    @ResponseBody
    @RequestMapping("/query")
    public ToJson<DocumentExchangeReceive> query(PageParams pageParams, HttpServletRequest request) {
        return documentExchangeReceiveService.query(pageParams, request);
    }
    // 删除多条数据(内部收文，外部收文均可使用)
    @ResponseBody
    @RequestMapping("/delete")
    public ToJson delete(String receiveIds) {
        return documentExchangeReceiveService.delete(receiveIds);
    }
    // 收文接口
    @ResponseBody
    @RequestMapping("/receiveDoc")
    public ToJson<Object> receiveDoc(
            Integer fflowId,
            @RequestParam(value = "fflowStep", required = false) Integer fflowStep,
            @RequestParam(value = "fprcsId", required = false) String fprcsId,
            @RequestParam(value = "frunName", required = false) String frunName
            , DocumentModelWithBLOBs document, HttpServletRequest request, String fromRunId, String
                    receiveId, String attachmentId, String attachmentName) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        String userId = (String) request.getSession().getAttribute("userId");
        Integer deptId = (Integer) request.getSession().getAttribute("deptId");
        document.setCurUserId(userId);
        document.setCreater(userId);
        document.setCreateDept(String.valueOf(deptId));
       /* document.setDocumentType("1");
        document.setDispatchType("documentDecision");
        frunName="22";
        attachmentId="11609@2002_406374811";
        attachmentName="教学管理系统的概念模型设计.docx*";
        fromRunId="1352";
        fflowId=264;
        receivedId="11";*/
        DocumentExchangeReceive documentExchangeReceive = new DocumentExchangeReceive();

        ToJson<Object> result = documentSerivce.saveDocument2(user, fflowId, fflowStep, fprcsId, frunName, document, request, fromRunId, attachmentId, attachmentName);
        //  documentExchangeReceiveService.receiveDoc(documentExchangeReceive);
        DocumentModelWithBLOBs documentModelWithBLOBs = (DocumentModelWithBLOBs) result.getObject();
        Integer runId = documentModelWithBLOBs.getRunId();
        documentExchangeReceive.setReceiveRunId(runId);
        documentExchangeReceive.setReceiveId(Integer.parseInt(receiveId));
        documentExchangeReceiveService.receiveDoc(documentExchangeReceive, request);
        return result;
    }

    // 收文操作后去除事务提醒lsa
    @ResponseBody
    @RequestMapping("/cancel")
    public void cancel(HttpServletRequest request, Integer receiveId) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        smsService.updatequerySmsByType("70", user.getUserId(), ("/document/receive?receiveId=" + receiveId));
    }

    //待收集团公文lsa
    @ResponseBody
    @RequestMapping("/Receive")
    public ToJson Receive(HttpServletRequest request) throws IOException {
        ToJson toJson=new ToJson();
        try {
            //ClientReceive1公文下载完成事件,子类可以重写本方法监听文档的下载完成事件 将公文信息保存到各自OA系统中
            ClientReceive1 clientReceive = new ClientReceive1() {
                protected void onDownloaded(Document document) {
                    System.out.println("下载公文完成，开始处理：将临时目录文件保存到各个OA系统中");
                    onDocumentDownloaded(document, this);
                }
            };
            DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
            clientReceive.setDTRootUrl(documentOutConfig.getOutSysUrl());
            clientReceive.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            //clientReceive.setLocalTempDir("c:/temp/");//默下载路径为 c:/exchangetemp/
            String result = clientReceive.getReceivingDocuments();
            System.out.println("待收公文列表：" + result);
            JSONObject json = new JSONObject(result);
            JSONArray arr = json.getJSONArray("list");
            int len = arr.length();
            for (int i = 0; i < len; i++) {
                JSONObject obj = arr.getJSONObject(i);
                String unids = obj.getString("wrapperid");
                clientReceive.setRequestDocuments(unids, "", "");
                clientReceive.download();
            }
            toJson.setFlag(0);
            toJson.setMsg("已收下"+len+"个公文");
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg("数据异常");
        }
         return toJson;
    }

    // 集团收文接口lsa
    @ResponseBody
    @RequestMapping("/receives")
    public ToJson<Object> receive(
            Integer fflowId,
            @RequestParam(value = "fflowStep", required = false) Integer fflowStep,
            @RequestParam(value = "fprcsId", required = false) String fprcsId,
            @RequestParam(value = "frunName", required = false) String frunName
            , DocumentModelWithBLOBs document, HttpServletRequest request, String receiveId, String
                    attachmentId, String attachmentName) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        String userId = (String) request.getSession().getAttribute("userId");
        Integer deptId = (Integer) request.getSession().getAttribute("deptId");
        document.setCurUserId(userId);
        document.setCreater(userId);
        document.setCreateDept(String.valueOf(deptId));
        DocumentExchangeReceive documentExchangeReceive = new DocumentExchangeReceive();
        ToJson<Object> result = documentSerivce.saveDocument2(user, fflowId, fflowStep, fprcsId, frunName, document, request, "", attachmentId, attachmentName);
        DocumentModelWithBLOBs documentModelWithBLOBs = (DocumentModelWithBLOBs) result.getObject();
        Integer runId = documentModelWithBLOBs.getRunId();
        documentExchangeReceive.setReceiveRunId(runId);
        documentExchangeReceive.setReceiveId(Integer.parseInt(receiveId));
        documentExchangeReceiveService.receiveDoc(documentExchangeReceive, request);
        return result;
    }

    /**
     * OA系统需要将这些信息保存到各自系统中：公文属性、公文附件文档
     * lsa
     *
     * @param doc
     * @param clientReceiver
     */
    private void onDocumentDownloaded(Document doc, ClientReceive1 clientReceiver) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 初始化流程文档
            StringBuffer attachmentId = new StringBuffer();//附件id串
            StringBuffer attachmentId2 = new StringBuffer();//正文id
            StringBuffer attachmentName = new StringBuffer();//附件名称
            StringBuffer attachmentName2 = new StringBuffer();//正文名称
            // 下载并保存正文附件
            java.util.List accs = doc.getAccessories(); // 正文附件列表集合
            if (accs != null && !accs.isEmpty()) {
                java.util.Iterator itr = accs.iterator(); // 正文附件列表集合迭代器
                int accIdx = 0; // 已下载正文附件计数
                boolean isMSS = false; // 是作为正文还是附件保存的标记（true为正文或者原文）
                String tmpFN = null;// 下载的正文附件本地路径
                for (Iterator iterator2 = accs.iterator(); iterator2.hasNext(); ) {
                    Accessory acc = (Accessory) iterator2.next();
                    acc = (Accessory) itr.next();
                    if (acc == null) continue;
                    Reference accType = acc.getAccessoryType();
                    //判断是否是转版正文或者原文true  false表示附件
                    isMSS = accType != null && ClientReceive1.isDocAccessory(accType.getUnid());
                    String extName = StringUtil.stringRight(acc.getPath(), ".", 0); // 文件扩展名
                    String FN = acc.getUNID() + "." + extName; // 下载的正文附件本地文件名
                    System.out.println("FN:" + FN);
                    tmpFN = clientReceiver.getAccessoryFile(acc);
                    if (tmpFN == null) throw new IOException("下载的附件本地临时文件为空！");

                    if (isMSS == true) {
                        if (accType.getUnid().indexOf(ACT_actNoStampDoc) >= 0) {
                            System.out.println("判断是否未盖章正文ceb==" + FN);
                        } else if (accType.getUnid().indexOf(ACT_actStampDoc) >= 0) {
                            System.out.println("判断是否已盖章正文ceb==" + FN);
                        } else if (accType.getUnid().indexOf(ACT_actCommonDoc) >= 0) {
                            System.out.println("判断是否公文原文doc==" + FN);
                        }
                    } else {
                        if (accType.getUnid().indexOf(ACT_actAttachment) >= 0) {
                            System.out.println("判断是否公文附件==" + FN);
                        }
                    }
                    File tmpFile = new File(tmpFN); // 下载的正文附件本地临时文件
                    accIdx++;
                    if (tmpFile.exists()) {
                        FileInputStream fileInputStream = null;
                        fileInputStream = new FileInputStream(tmpFile);
                        if (isMSS == true) {//正文，文件标题改为文件标题
                            //文件后缀名
                            String suffix = tmpFile.getName().substring(tmpFile.getName().lastIndexOf(".") + 1);
                            String fileName = doc.getItemValue("fld_subject") + "." + suffix;
                            MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                            MultipartFile[] multipartFiles = new MultipartFile[1];
                            multipartFiles[0] = multipartFile;
                            //将文件上传，并对应的id和那name存放到document_exchange_receive表
                            ToJson<Attachment> attachmentToJson = enclosureController.uploadEnterprise(multipartFiles, "document", "xoa1001", request, response);
                            Object[] o = FileUploadUtil.reAttachment(attachmentToJson.getObj());
                            //正文或者原文
                            attachmentId2.append(((o[0].toString().split(",")[0]) + ","));
                            attachmentName2.append(((o[1].toString().split("\\*")[0]) + "\\*"));
                            //将本地文件删除
                            tmpFile.delete();
                        } else {//附件就获取文件原名
                            MultipartFile multipartFile = new MockMultipartFile(acc.getName(), acc.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                            MultipartFile[] multipartFiles = new MultipartFile[1];
                            multipartFiles[0] = multipartFile;
                            //将文件上传，并对应的id和那name存放到document_exchange_receive表
                            ToJson<Attachment> attachmentToJson = enclosureController.uploadEnterprise(multipartFiles, "workflow", "xoa1001", request, response);
                            Object[] o = FileUploadUtil.reAttachment(attachmentToJson.getObj());
                            attachmentId.append(((o[0].toString().split(",")[0]) + ","));
                            attachmentName.append(((o[1].toString().split("\\*")[0]) + "\\*"));
                            //将本地文件删除
                            tmpFile.delete();
                        }

                    }
                }
            }
            //将记录存放至联网收文表
            DocumentExchangeReceive documentExchangeReceive = new DocumentExchangeReceive();
            documentExchangeReceive.setReceiveDeptId(1);//接收单位
            documentExchangeReceive.setDocTitle(doc.getItemValue("fld_subject"));//文件标题
            documentExchangeReceive.setDocNo(doc.getItemValue("fld_docnum"));//文件字号
            documentExchangeReceive.setFromUnit(doc.getItemValue("fld_senddept"));// 来文单位
            documentExchangeReceive.setFromTime(sf.parse(doc.getItemValue("fld_senddate")));// 发送时间
            documentExchangeReceive.setReceiveStatus("0");//阅读状态
            documentExchangeReceive.setReceiveUnit(doc.getItemValue("_receiveUN"));// 接收单位
            documentExchangeReceive.setAttachmentId(attachmentId.toString());//附件id串
            documentExchangeReceive.setAttachmentId2(attachmentId2.toString());//正文id
            documentExchangeReceive.setAttachmentName(attachmentName.toString());//附件名称串
            documentExchangeReceive.setAttachmentName2(attachmentName2.toString());//正文名称
            documentExchangeReceiveService.insert(documentExchangeReceive);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    //向集团发文lsa
    @ResponseBody
    @RequestMapping("/send")
    public ToJson Send(
            HttpServletRequest request, Integer runId) throws IOException {
        ToJson json = new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);//当前登陆人的信息
        String[] splits = request.getParameter("ouIds").split(",");//发送的外部单位对应的id
        StringBuffer units = new StringBuffer();
        for (int i = 0; i < splits.length; i++) {
            DocumentExchangeOutUnit documentExchangeOutUnit1 = documentExchangeOutUnitService.selectById(Integer.parseInt(splits[i]));
            if (i == (splits.length - 1)) {
                units.append(documentExchangeOutUnit1.getDeptName());
            } else {
                units.append(documentExchangeOutUnit1.getDeptName() + ",");
            }
        }
        String AttachmentNames = request.getParameter("AttachmentNames");//需要发送的附件名称串
        String AttachmentIds = request.getParameter("AttachmentIds");//需要发送的附件id串
        String remark = request.getParameter("remark");//备注
        String sqlType = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
        String company = sqlType;
        DocumentModel documents = documentModelMapper.checkRunId(runId);//获取当前公文的所有信息
        String deptNameById = departmentMapper.getDeptNameById(Integer.parseInt(documents.getCreateDept()));//拟稿部门
        int attachNum = AttachmentIds.split(",").length;//附件数量
        //获取当前流程实例
        FlowRun flowRun = flowRunMapper.find(runId);
        //获取业务接口
        FlowHookWithBLOBs flowHook = flowHookMapper.queryByHmodule("document", String.valueOf(flowRun.getFlowId()));
        //头表单
        org.jsoup.nodes.Document headDoc = null;
        Map<String, org.jsoup.nodes.Document> documentMap = null;
        documentMap = workController.flowMapping(flowRun);
        headDoc = documentMap.get("headDocument");
        if (flowHook != null) {
            String relation = flowHook.getMap();//映射分割
            String[] mappingArray = relation.split(",");
            List<String> key = new ArrayList<>();
            List<String> value = new ArrayList<>();
            for (String mapping : mappingArray) {
                String[] mappingHeadAndEnd = mapping.split("=>");
                if (mappingHeadAndEnd.length > 1) {
                    String mappingHead = mappingHeadAndEnd[0];//映射头
                    String mappingEnd = mappingHeadAndEnd[1];//映射尾
                    String headData = HtmlUtil.getDocumentName(headDoc, mappingHead);
                    if (headData != null && !headData.trim().equals("")) {
                        value.add(mappingEnd);
                        key.add(headData);
                    }

                }

            }
            List<String> values = new ArrayList<>();
            if (key.size() > 0) {
                Map<String, Object> valueMap = workMapper.getDataValue(key, flowRun.getRunId(), "flow_data_" + flowRun.getFlowId());
                if (valueMap != null) {
                    for (String k : key) {
                        Object v = valueMap.get(k);
                        if (v != null) {
                            values.add(String.valueOf(v));
                        } else {
                            values.add("");
                        }
                    }
                }
            }
            //获取文号，标题
            for (int k = 0; k < key.size(); k++) {
                if ("title".equals(value.get(k))) {
                    documents.setTitle(values.get(k));
                }
                if ("doc_no".equals(value.get(k))) {
                    documents.setDocNo(values.get(k));
                }
            }
        }
        Document document = new DocumentImpl();
        Hashtable items = new Hashtable();
        DateTime dt = new DateTime();
        String DTString = dt.getNowDTString();
        //2014-11-24 00:19:49
        String DTDate = dt.getDate();
        items.put("fld_subject", documents.getTitle());//公文主题
        items.put("fld_draftdate", DTDate);//拟稿日期
        if (!StringUtils.checkNull(documents.getDocNo())) {
            items.put("fld_docnum", (documents.getDocNo()));//公文文号
        }else{
            items.put("fld_docnum", "");//公文文号
        }
        if (!StringUtils.checkNull(documents.getKeyWord())) {
            items.put("fld_keyword", documents.getKeyWord());//关键字（允许为空）
        }else{
            items.put("fld_keyword","");//关键字（允许为空）
        }
        if(!StringUtils.checkNull(documents.getCreater())){
            items.put("fld_drafter", usersService.getUserNameById(documents.getCreater()));//拟稿人
        }
        items.put("fld_draftdept", deptNameById);//拟稿部门
        items.put("fld_filetype", "公文发文");//文件类型包括：1、集团公司发文；2、公司发文；3、部门发文； 4、党委发文；
        items.put("fld_docdirection", "上行文");//公文类型：1、上行文；2、平(下)行文
        if(!StringUtils.checkNull(documents.getDispatchType())){
            try{
                SysCode sysCode=new SysCode();
                sysCode.setCodeNo(documents.getDispatchType());
                SysCode codeByCodeNo = sysCodeService.getCodeByCodeNo(sysCode);
                items.put("fld_doctype",codeByCodeNo.getCodeName());//公文种类
            }catch (Exception e){

            }

        }else{
            items.put("fld_doctype","");//公文种类
        }
        items.put("fld_signdate", DTString);//签发日期
        //主送单位和发送单位参数一致
        items.put("fld_mainsend", new String((units.toString()).getBytes("GBK"), "GBK"));//主送单位
        items.put("fld_sendunits", new String((units.toString()).getBytes("GBK"), "GBK"));//发送单位
        items.put("fld_signer", documents.getCreater());
        items.put("fld_accessorynum", attachNum);//附件数量
        String s = String.valueOf(documents.getPages());
        if (s != null && s != "null" && s !="") {
            items.put("fld_page_count", documents.getPages());//正文页数
        }
        Users usersByuserId = usersService.getUsersByuserId(user.getUserId());
        items.put("fld_memo", remark);
        items.put("fld_senddept", usersByuserId.getDeptName());
        items.put("fld_senddate", DTString);

        if(!StringUtils.checkNull(usersByuserId.getMobilNo())){
            items.put("fld_mobile", usersByuserId.getMobilNo());    //新增发文用户手机号码
        }
        document.setItems(items);

        //1、默认附件收文单位都可见。2、以下代码可以单独设置附件分发表:指定附件分发给各单位。
        //Map accTable = new HashMap();
        //accTable.put("办公厅", "test11.pdf");
        //accTable.put("中国cs测试2", "aa.txt");
        //document.replaceItemValue("_accessorytable", accTable);
        DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
        ClientSend clientSend = new ClientSend1();
        clientSend.setDTRootUrl(documentOutConfig.getOutSysUrl());
        clientSend.setDocument(document, "", "");
        //测试用户User=中国cs测试
        clientSend.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        //附件
        List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(AttachmentNames, AttachmentIds, sqlType, "workflow");
        for (Attachment attachment : attachments) {

            //---------------------------------判断是否为Linux开始-------------------------------------
            String attachmentName = attachment.getAttachName();
            try {
                int codeLength = attachmentName.getBytes("UTF-8").length;
                String type = attachmentName.substring(attachmentName.lastIndexOf("."));
                if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                    String str = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                    String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                    attachmentName=(Pattern.compile(regEx).matcher(str).replaceAll("").trim().substring(0,100))+type;
                }
            }catch (Exception e){

            }
            //---------------------------------判断是否为Linux结束-------------------------------------

            StringBuffer atts = new StringBuffer();
            atts.append(sb);
            if (StringUtils.checkNull(atts.toString())) {
                String a = request.getRealPath("");
                atts.append(a);
                atts.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("workflow").append(System.getProperty("file.separator")).append(attachment.getYm()).
                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            } else {
                atts.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("workflow").append(System.getProperty("file.separator")).append(attachment.getYm()).

                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            }
            String path = atts.toString();
            Accessory accessory = new Accessory();
            Reference type = new Reference();
            type.setUnid(ACT_actAttachment);
            accessory.setAccessoryType(type);
            accessory.setName(attachment.getAttachName());
            accessory.setPath(attachment.getAttachName());
            File f = new File(path);
            FileInputStream fi = new FileInputStream(f);
            clientSend.addAccessory(accessory, fi, (int) f.length());
        }

        //正文
        List<Attachment> mainFile = GetAttachmentListUtil.returnAttachment(documents.getMainFileName(), documents.getMainFile(), sqlType, "document");
        for (Attachment attachment : mainFile) {
            //---------------------------------判断是否为Linux开始-------------------------------------
            String attachmentName = attachment.getAttachName();
            try {
                int codeLength = attachmentName.getBytes("UTF-8").length;
                String type = attachmentName.substring(attachmentName.lastIndexOf("."));
                if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                    String str = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                    String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                    attachmentName=(Pattern.compile(regEx).matcher(str).replaceAll("").trim().substring(0,100))+type;
                }
            }catch (Exception e){

            }
            //---------------------------------判断是否为Linux结束-------------------------------------
            StringBuffer mainfile = new StringBuffer();
            mainfile.append(sb);
            if (StringUtils.checkNull(mainfile.toString())) {
                String a = request.getRealPath("");
                mainfile.append(a);
                mainfile.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("document").append(System.getProperty("file.separator")).append(attachment.getYm()).
                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            } else {
                mainfile.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("document").append(System.getProperty("file.separator")).append(attachment.getYm()).

                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            }
            String path = mainfile.toString();
            Accessory accessory = new Accessory();
            Reference type = new Reference();
            type.setUnid(ACT_actCommonDoc);
            accessory.setAccessoryType(type);
            accessory.setName(attachment.getAttachName());
            accessory.setPath(attachment.getAttachName());
            File f = new File(path);
            FileInputStream fi = new FileInputStream(f);
            clientSend.addAccessory(accessory, fi, (int) f.length());
        }
        //版式正文
        List<Attachment> mainAipFile = GetAttachmentListUtil.returnAttachment(documents.getMainAipFileName(), documents.getMainAipFile(), sqlType, "document");
        for (Attachment attachment : mainAipFile) {
            //---------------------------------判断是否为Linux开始-------------------------------------
            String attachmentName = attachment.getAttachName();
            try {
                int codeLength = attachmentName.getBytes("UTF-8").length;
                String type = attachmentName.substring(attachmentName.lastIndexOf("."));
                if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                    String str = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                    String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                    attachmentName=(Pattern.compile(regEx).matcher(str).replaceAll("").trim().substring(0,100))+type;
                }
            }catch (Exception e){

            }
            //---------------------------------判断是否为Linux结束-------------------------------------
            StringBuffer mainAipfile = new StringBuffer();
            mainAipfile.append(sb);
            if (StringUtils.checkNull(mainAipfile.toString())) {
                String a = request.getRealPath("");
                mainAipfile.append(a);
                mainAipfile.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("document").append(System.getProperty("file.separator")).append(attachment.getYm()).
                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            } else {
                mainAipfile.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("document").append(System.getProperty("file.separator")).append(attachment.getYm()).

                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachmentName);
            }
            String path = mainAipfile.toString();
            Accessory accessory = new Accessory();
            Reference type = new Reference();
            //type.setUnid(ACT_actStampDoc);//盖章公文
            type.setUnid(ACT_actNoStampDoc);//未盖章公文
            accessory.setAccessoryType(type);
            accessory.setName(attachment.getAttachName());
            accessory.setPath(attachment.getAttachName());
            File f = new File(path);
            FileInputStream fi = new FileInputStream(f);
            clientSend.addAccessory(accessory, fi, (int) f.length());
        }
        /*//新增公文原文
        accessory = new Accessory();
        type = new Reference();
        type.setUnid(ACT_actCommonDoc);
        accessory.setAccessoryType(type);
        accessory.setName("cs公文测试001.docx");
        accessory.setPath("cs公文测试001.docx");
        File f = new File("c:/cs公文测试001.docx");
        FileInputStream fi = new FileInputStream(f);
        clientSend.addAccessory(accessory, fi, (int) f.length());

        accessory = new Accessory();
        type = new Reference();
        //type.setUnid(ACT_actStampDoc);//盖章公文
        type.setUnid(ACT_actNoStampDoc);//未盖章公文
        accessory.setAccessoryType(type);
        accessory.setName("公文传输测试文件.ceb");
        accessory.setPath("公文传输测试文件.ceb");
        f = new File("c:/公文传输测试文件.ceb");
        fi = new FileInputStream(f);
        clientSend.addAccessory(accessory, fi, (int) f.length());*/
        boolean isSuccess = clientSend.sendDocument();
        if (isSuccess) {
            System.out.println("发送公文成功!");
            System.out.println(document.getUNID() + "unid=发送公文成功后对应的公文UNID应保持到本地OA系统作为记录，用于以后补发和收回等操作使用");
            for (String spl : splits) {
                DocumentExchangeOutUnit documentExchangeOutUnit1 = documentExchangeOutUnitService.selectById(Integer.parseInt(spl));
                DocumentOutSendRecordWithBLOBs documentOutSendRecordWithBLOBs = new DocumentOutSendRecordWithBLOBs();
                documentOutSendRecordWithBLOBs.setDeptNames(documentExchangeOutUnit1.getDeptName());//documentExchangeOutUnit.getDeptName()
                documentOutSendRecordWithBLOBs.setOunitNames(documentExchangeOutUnit1.getOunitFullName());//documentExchangeOutUnit.getOunitFullName()
                documentOutSendRecordWithBLOBs.setRunId(runId);
                documentOutSendRecordWithBLOBs.setSendTime(new Date());
                documentOutSendRecordWithBLOBs.setDocUnid(document.getUNID());
                documentOutSendRecordWithBLOBs.setRemark(remark);
                documentOutSendRecordWithBLOBs.setSendType("首发");
                documentOutSendRecordWithBLOBs.setReceiveStatus("待接收");
                documentOutSendRecordService.insert(documentOutSendRecordWithBLOBs);
            }
        } else {
            System.out.println("发送公文失败!");
        }
        clientSend.clear();
        json.setFlag(0);
        json.setMsg("发送公文成功!");
        return json;
    }

    //向集团补发公文 lsa
    @ResponseBody
    @RequestMapping("/AppendSend")
    public ToJson AppendSend(HttpServletRequest request, Integer runId, String ouIds) {
        String remark = request.getParameter("remark");//备注
        ToJson json = new ToJson();
        List<String> list = documentOutSendRecordService.selectUnidByRunId(runId);
        for (String unid : list) {
            DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
            ClientSend clientSend = new ClientSend1();
            clientSend.setDTRootUrl(documentOutConfig.getOutSysUrl());
            //测试用户User=中国cs测试
            clientSend.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            String[] splits = ouIds.split(",");//发送的外部单位对应的id
            StringBuffer units = new StringBuffer();
            for (int i = 0; i < splits.length; i++) {
                DocumentExchangeOutUnit documentExchangeOutUnit1 = documentExchangeOutUnitService.selectById(Integer.parseInt(splits[i]));
                if (i == (splits.length - 1)) {
                    units.append(documentExchangeOutUnit1.getDeptName());
                } else {
                    units.append(documentExchangeOutUnit1.getDeptName() + ",");
                }
            }
            boolean isSuccess = clientSend.appendSend(unid, units.toString(), "");
            if (isSuccess) {
                System.out.println("补发公文成功!");
                //补发成功本地数据需要保存一份
                for (String spl : splits) {
                    DocumentExchangeOutUnit documentExchangeOutUnit1 = documentExchangeOutUnitService.selectById(Integer.parseInt(spl));
                    DocumentOutSendRecordWithBLOBs documentOutSendRecordWithBLOBs = new DocumentOutSendRecordWithBLOBs();
                    documentOutSendRecordWithBLOBs.setDeptNames(documentExchangeOutUnit1.getDeptName());//documentExchangeOutUnit.getDeptName()
                    documentOutSendRecordWithBLOBs.setOunitNames(documentExchangeOutUnit1.getOunitFullName());//documentExchangeOutUnit.getOunitFullName()
                    documentOutSendRecordWithBLOBs.setRunId(runId);
                    documentOutSendRecordWithBLOBs.setDocUnid(unid);
                    documentOutSendRecordWithBLOBs.setSendTime(new Date());
                    documentOutSendRecordWithBLOBs.setRemark(remark);
                    documentOutSendRecordWithBLOBs.setSendType("补发");
                    documentOutSendRecordWithBLOBs.setReceiveStatus("待签收");
                    documentOutSendRecordService.insert(documentOutSendRecordWithBLOBs);
                }
                json.setFlag(0);
                json.setMsg("补发公文成功!");
            } else {
                System.out.println("补发公文失败!");
                json.setFlag(1);
                json.setMsg("补发公文失败!");
            }
            clientSend.clear();
        }
        return json;
    }

    //收回集团公文lsa
    @ResponseBody
    @RequestMapping("/Regain")
    public ToJson Regain(HttpServletRequest request) throws IOException {
        ToJson json = new ToJson();
        String datas = request.getParameter("datas");
        com.alibaba.fastjson.JSONArray jsons = new com.alibaba.fastjson.JSONArray();
        List<Map> list = jsons.parseObject(datas, List.class);
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            //unidList需要调用公文签收情况表方法获取数据遍历得到该List
            String recordId = map.get("recordId").toString();//recordId，docUnid，unitUnid
            List unidList = new ArrayList();
            //联网公文UNID
            String docUNID = map.get("docUnid").toString();
            //跟踪记录的unid字符串数组
            String unitUnid = map.get("unitUnid").toString();
            unidList.add(unitUnid);

            //unidList.add("0936F1C1A9F63D56B51AECB207DE1FB6");

            DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
            ClientSend1 clientSend = new ClientSend1();
            clientSend.setDTRootUrl(documentOutConfig.getOutSysUrl());
            //测试用户User=中国cs测试
            clientSend.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            //int 0:收回成功    int -1：收回失败
            int isSuccess = clientSend.regain(unidList, docUNID);
            if (isSuccess == 0) {
                System.out.println("");
                DocumentOutSendRecordWithBLOBs document = new DocumentOutSendRecordWithBLOBs();
                document.setRecordId(Integer.parseInt(recordId));
                document.setReceiveStatus("已收回");
                documentOutSendRecordService.updateById(document);
                json.setMsg("联网收回成功!");
                json.setFlag(0);
            } else {
                json.setMsg("联网收回失败!");
                json.setFlag(0);
            }
        }
        return json;
    }

    //签收情况表lsa
    @ResponseBody
    @RequestMapping("/GetDocumentTracing")
    public ToJson GetDocumentTracing(Integer runId) throws IOException {
        ToJson json = new ToJson();
        this.DocumentTracing(runId);//更新签收时间和状态
        List<DocumentOutSendRecordWithBLOBs> documentOutSendRecords = documentOutSendRecordService.selectByRunId(runId);
        json.setObj(documentOutSendRecords);
        json.setFlag(0);
        return json;
    }

    public void DocumentTracing(Integer runId) throws IOException {
        try {
            //获取关于此条流程的所有发送情况
            List<DocumentOutSendRecordWithBLOBs> documentOutSendRecords = documentOutSendRecordService.selectByRunId(runId);
            ClientReceive1 clientReceive = new ClientReceive1();
            DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
            clientReceive.setDTRootUrl(documentOutConfig.getOutSysUrl());
            //测试用户User=中国cs测试
            clientReceive.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            //公文的唯一表示UNID 与待收公文中unid一致
            for (DocumentOutSendRecord dos : documentOutSendRecords) {
                String unid = dos.getDocUnid();
                List result = clientReceive.getDocumentTracing(unid);
                if (result != null && result.size() > 0) {
                    for (int i = 0; i < result.size(); i++) {
                        DocumentOutSendRecordWithBLOBs document = new DocumentOutSendRecordWithBLOBs();
                        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Document doc = (Document) result.get(i);
                        Hashtable items = doc.getItems();
                        document.setRecordId(dos.getRecordId());
                        document.setUnitUnid(String.valueOf(items.get("unid")));
                        document.setSendTime(ft.parse(String.valueOf(items.get("sendtime"))));
                        //这个会将首发的状态改为补发，补发是根据对应的unid进行补发，unid是相同的
                        document.setSendType(String.valueOf(items.get("sendtype")));
                        document.setReceiveStatus(String.valueOf(items.get("status")));
                        if (!StringUtils.checkNull(String.valueOf(items.get("receivetime")))) {
                            document.setReceiveTime(ft.parse(String.valueOf(items.get("receivetime"))));
                        }
                        documentOutSendRecordService.updateById(document);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //分发情况数据获取lsa
    public List shuju(String unid) throws IOException {
        List result = new ArrayList();
        try {
            ClientReceive1 clientReceive = new ClientReceive1();
            DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
            clientReceive.setDTRootUrl(documentOutConfig.getOutSysUrl());
            //测试用户User=中国cs测试
            clientReceive.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            //公文的唯一表示UNID 与待收公文中unid一致
            result = clientReceive.getDocumentTracing(unid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //退回功能   暂未开发lsa
    @ResponseBody
    @RequestMapping("/SendBack")
    public void SendBack(String unid, String backReason) throws IOException {
        DocumentOutConfig documentOutConfig = documentOutConfigMapper.selectByPrimaryKey(1);
        try {
            ClientReceive1 clientReceive = new ClientReceive1();
            clientReceive.setDTRootUrl(documentOutConfig.getOutSysUrl());
            //测试用户User=中国cs测试
            clientReceive.setUser(documentOutConfig.getOutSysUser(), documentOutConfig.getOutSysPwd());
            Map params = new HashMap();
            //unid表示本单位已签收的本份公文=wrapperid
            params.put("unid", unid);
            params.put("backReason", backReason);
            clientReceive.sendBack(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //内部公文收回
    @ResponseBody
    @RequestMapping("/recoverDoc")
    public ToJson recoverDoc(HttpServletRequest request){
        return documentExchangeReceiveService.recoverDoc(request);
    }
    //根据主键查询一条数据
    @ResponseBody
    @RequestMapping("/queryById")
    public ToJson queryById(DocumentExchangeReceive documentExchangeReceive){
        return documentExchangeReceiveService.queryById(documentExchangeReceive);
    }

    @ResponseBody
    @RequestMapping("/returnComments")
    public ToJson returnComments(DocumentExchangeReceive documentExchangeReceive, HttpServletRequest request){
        ToJson json = new ToJson();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        try {
            documentExchangeReceive.setReceiveTime(new Date());
            documentExchangeReceive.setReceiveUser(users.getUserId());
            int i = documentExchangeReceiveMapper.updateByPrimaryKeySelective(documentExchangeReceive);
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
    @ResponseBody
    @RequestMapping("/queryByReturn")
    public ToJson queryByReturn(HttpServletRequest request, String receiveStatus, Integer page, Integer limit, boolean useFlag){
        return documentExchangeReceiveService.queryByReturn(request,receiveStatus,page,limit,useFlag);
    }
}
